import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/pages/schooladmin/accountListItems.dart';
import 'package:ichinesereader/pages/schooladmin/booksDataList.dart';
import 'package:ichinesereader/pages/schooladmin/schoolReportsList.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/bookrelease.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerSchoolAdmin.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/sidebars/settingsBarHorizontal.dart';
import '../../themes/appTheme.dart';
import '../../themes/pageStyles.dart';
import '../../widgets/sidebars/adminSidebar.dart';

class SchoolAdminHome extends StatefulWidget {
  static const String routeName = '/schooladmin/home';

  @override
  _SchoolAdminHomeState createState() => _SchoolAdminHomeState();
}

class _SchoolAdminHomeState extends State<SchoolAdminHome> {
  final SchoolAdminController _schoolAdminController = Get.find();
  final BooksController _booksController = Get.find();
  final box = Hive.box('appconfig');
  final PageStyles _pageStyles = PageStyles();

  @override
  void initState() {
    super.initState();
    int locale = box.get('locale', defaultValue: 0);
    bool isDark = box.get('theme', defaultValue: 0) == 1;

    Future.delayed(Duration(milliseconds: 100), () {
      _schoolAdminController.fetchSchoolOverviewData();
      // if (_schoolAdminController.schoolOverviewData.value.schoolName == null) {
      //   _schoolAdminController.fetchSchoolOverviewData();
      // }
      _schoolAdminController.fetchSchoolAdminProfile();
      // if (_schoolAdminController.schoolAdminProfile.value.userId == null) {
      //   _schoolAdminController.fetchSchoolAdminProfile();
      // }
      _schoolAdminController.fetchSchoolBasicStatics();
      // if (_schoolAdminController.schoolBasicStatics.value.result == null) {
      //   _schoolAdminController.fetchSchoolBasicStatics();
      // }
      if (_booksController.booksDataSummary.value.result == null) {
        _booksController.fetchBooksDataSummary();
      }
      if (_booksController.bookRelease.value.result == null) {
        _booksController.getNewBooksDataForDays(10);
      }
      _schoolAdminController.fetchSchoolActivities();
      // if (_schoolAdminController.schoolActivities.value.result == null) {
      //   _schoolAdminController.fetchSchoolActivities();
      // }
      _schoolAdminController.fetchSchoolAllClassesDetailsWithoutAll();

      if (isDark) {
        Get.changeThemeMode(ThemeMode.dark);
      } else {
        Get.changeThemeMode(ThemeMode.light);
      }

      if (locale == 0) {
        Get.updateLocale(Locale('en', 'US'));
      }
      if (locale == 1) {
        Get.updateLocale(Locale('zh', 'CN'));
      }
      if (locale == 2) {
        Get.updateLocale(Locale('zhHant', 'TW'));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    Log.debug("build temp SchoolAdminHome");

    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;

    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: isSmallScreen ? CustomAppBar(title: 'Home') : null,
      drawer: isSmallScreen ? SchoolAdminAppDrawer() : null,
      body: Container(
        decoration: _pageStyles.pageBoxDecoration(),
        child: Row(
          children: [
            Visibility(
                visible: !isSmallScreen,
                child:
                    AdminSidebarX(selectedIndex: 0, isBigScreen: isBigScreen)),
            //MAIN
            Expanded(
              flex: 5,
              child: Container(
                margin: EdgeInsets.fromLTRB(0.0, 33.0, 12.0, 33.0),
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: Column(
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          color: Get.isDarkMode
                              ? AppTheme.colors.darkTheme2
                              : Colors.white.withOpacity(0.3),
                          borderRadius: BorderRadius.circular(3.0),
                          boxShadow: [
                            BoxShadow(
                              blurRadius: 3,
                              spreadRadius: 1,
                              color: Get.isDarkMode
                                  ? Colors.transparent
                                  : Colors.black.withOpacity(0.1),
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        margin: EdgeInsets.only(
                          bottom: 9.0,
                        ),
                        padding: EdgeInsets.all(
                          12.0,
                        ),
                        //TOP BAR AREA
                        child: Row(
                          children: [
                            _schoolAdminController.obx((data) {
                              if (_schoolAdminController
                                      .schoolAdminProfile.value.school !=
                                  null) {
                                return Flexible(
                                  child: RichText(
                                    overflow: TextOverflow.fade,
                                    text: TextSpan(
                                      children: <TextSpan>[
                                        TextSpan(
                                          text:
                                              '${_schoolAdminController.schoolAdminProfile.value.school!.schoolName.toString()} : ${'Subscription Period'.tr} ${parseDate(_schoolAdminController.schoolAdminProfile.value.accountStartDate!)} - ${parseDate(_schoolAdminController.schoolAdminProfile.value.accountEndDate!)}',
                                          style: TextStyle(color: Colors.white),
                                        ),
                                        TextSpan(
                                          text:
                                              '\n(${'Your account will be expired in'.tr} ${parseDateDiff(DateTime.now().millisecondsSinceEpoch, _schoolAdminController.schoolAdminProfile.value.accountEndDate!)})',
                                          style: TextStyle(
                                              color: Get.isDarkMode
                                                  ? Colors.white54
                                                  : Colors.black),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              } else {
                                return Text('');
                              }
                            }),
                            Spacer(),
                            SettingsBarHorizontal(!isSmallScreen, 'NoToShow'),
                          ],
                        ),
                      ),
                      Container(
                        child: AccountListItem(),
                        margin: EdgeInsets.symmetric(vertical: 18.0),
                      ),
                      Divider(),
                      Container(
                        child: SchoolReportsList(),
                        margin: EdgeInsets.symmetric(vertical: 18.0),
                      ),
                      Divider(),
                      Container(
                        child: BooksDataList(),
                        margin: EdgeInsets.symmetric(vertical: 18.0),
                      ),
                      Divider(),
                      //BOOKS' INFORMATION AREA
                      isSmallScreen
                          ? Column(
                              //mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                Container(
                                  decoration: BoxDecoration(
                                    color: Get.isDarkMode
                                        ? AppTheme.colors.darkTheme2
                                        : Colors.white.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(6.0),
                                  ),
                                  padding: EdgeInsets.all(24.0),
                                  margin: EdgeInsets.symmetric(
                                    vertical: 12.0,
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        'Activities'.tr,
                                        style: TextStyle(
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Colors.black,
                                            fontFamily: 'Montserrat',
                                            fontSize: 21.0),
                                      ),
                                      Obx(
                                        () {
                                          final value = _schoolAdminController
                                              .schoolActivities
                                              .value
                                              .result
                                              ?.subResult;
                                          if (value != null) {
                                            return Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: value
                                                  .map(
                                                    (item) => Container(
                                                      width: double.infinity,
                                                      margin:
                                                          EdgeInsets.symmetric(
                                                              vertical: 6.0),
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 9.0),
                                                      decoration: BoxDecoration(
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(3.0),
                                                        color: Get.isDarkMode
                                                            ? Colors.black
                                                            : Colors.white
                                                                .withOpacity(
                                                                    0.3),
                                                      ),
                                                      child: Text(
                                                        "${parseDateWithTime(item.startDateUTC)}, ${item.firstName} ${item.lastName} created homework ${item.name} ",
                                                        maxLines: 1,
                                                        overflow:
                                                            TextOverflow.fade,
                                                        style: TextStyle(
                                                            color: Get.isDarkMode
                                                                ? Get.theme
                                                                    .primaryColorDark
                                                                : Colors.black,
                                                            fontFamily:
                                                                'Montserrat',
                                                            fontSize: 14.0),
                                                      ),
                                                    ),
                                                  )
                                                  .toList(),
                                            );
                                          } else {
                                            return Text('No activies'.tr);
                                          }
                                        },
                                      )
                                    ],
                                  ),
                                ),
                                //有封面的元件要放下方，否则图片会呈现于下方元件的后方，导致图和文字交叠的效果
                                Container(
                                    decoration: BoxDecoration(
                                      color: Get.isDarkMode
                                          ? AppTheme.colors.darkTheme2
                                          : Colors.white.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(6.0),
                                    ),
                                    padding: EdgeInsets.all(21.0),
                                    child: _booksController.obx(
                                      (data) {
                                        if (_booksController.booksDataSummary
                                                .value.result !=
                                            null) {
                                          return (Column(children: [
                                            Obx(() {
                                              if (_booksController
                                                  .bookReleaseData.isNotEmpty)
                                                return Container(
                                                  decoration: BoxDecoration(),
                                                  child: BookReleaseWidget(
                                                      bookReleaseData:
                                                          _booksController
                                                              .bookReleaseData),
                                                );
                                              else
                                                return Text('');
                                            })
                                          ]));
                                        } else {
                                          return Text('');
                                        }
                                      },
                                    )),
                              ],
                            )
                          : Container(
                              margin: EdgeInsets.only(top: 9.0),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                    child: Container(
                                        decoration: BoxDecoration(
                                          color: Get.isDarkMode
                                              ? AppTheme.colors.darkTheme2
                                              : Colors.white.withOpacity(0.1),
                                          borderRadius:
                                              BorderRadius.circular(6.0),
                                        ),
                                        padding: EdgeInsets.all(21.0),
                                        child: _booksController.obx(
                                          (data) {
                                            if (_booksController
                                                    .booksDataSummary
                                                    .value
                                                    .result !=
                                                null) {
                                              return (Column(children: [
                                                Padding(
                                                    padding:
                                                        const EdgeInsets.only(
                                                            left: 0,
                                                            right: 0,
                                                            top: 0,
                                                            bottom: 30),
                                                    child: Obx(() {
                                                      if (_booksController
                                                          .bookReleaseData
                                                          .isNotEmpty)
                                                        return Container(
                                                          child: BookReleaseWidget(
                                                              bookReleaseData:
                                                                  _booksController
                                                                      .bookReleaseData),
                                                        );
                                                      else
                                                        return Text('');
                                                    }))
                                              ]));
                                            } else {
                                              return Text('');
                                            }
                                          },
                                        )),
                                  ),
                                  ///////////////////ACTIVITY////////////////
                                  Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        color: Get.isDarkMode
                                            ? AppTheme.colors.darkTheme2
                                            : Colors.white.withOpacity(0.1),
                                        borderRadius:
                                            BorderRadius.circular(6.0),
                                      ),
                                      padding: EdgeInsets.all(21.0),
                                      margin: EdgeInsets.only(
                                        left: 9.0,
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            'Activities'.tr,
                                            style: TextStyle(
                                                color: Get.isDarkMode
                                                    ? Get.theme.primaryColorDark
                                                    : Get.theme
                                                        .primaryColorLight,
                                                fontFamily: 'Montserrat',
                                                fontSize: 21.0),
                                          ),
                                          Container(
                                              decoration: BoxDecoration(),
                                              child: Obx(
                                                () {
                                                  final value =
                                                      _schoolAdminController
                                                          .schoolActivities
                                                          .value
                                                          .result
                                                          ?.subResult;
                                                  if (value != null) {
                                                    return Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: value
                                                            .map(
                                                              (item) =>
                                                                  Container(
                                                                width: double
                                                                    .infinity,
                                                                margin: EdgeInsets
                                                                    .symmetric(
                                                                        vertical:
                                                                            6.0),
                                                                padding: EdgeInsets
                                                                    .symmetric(
                                                                  horizontal:
                                                                      9.0,
                                                                  vertical: 6.0,
                                                                ),
                                                                decoration:
                                                                    BoxDecoration(
                                                                  borderRadius:
                                                                      BorderRadius
                                                                          .circular(
                                                                              3.0),
                                                                  color: Get
                                                                          .isDarkMode
                                                                      ? Colors
                                                                          .black
                                                                      : Colors
                                                                          .white
                                                                          .withOpacity(
                                                                              0.3),
                                                                ),
                                                                child: Text(
                                                                  "${parseDateWithTime(item.startDateUTC)}, ${item.firstName} ${item.lastName} created homework ${item.name} ",
                                                                  maxLines: 1,
                                                                  overflow:
                                                                      TextOverflow
                                                                          .fade,
                                                                  style: TextStyle(
                                                                      color: Get.isDarkMode
                                                                          ? Get
                                                                              .theme
                                                                              .primaryColorDark
                                                                          : Colors
                                                                              .black,
                                                                      fontFamily:
                                                                          'Montserrat',
                                                                      fontSize:
                                                                          14.0),
                                                                ),
                                                              ),
                                                            )
                                                            .toList());
                                                  } else {
                                                    return Text(
                                                        'No activies'.tr);
                                                  }
                                                },
                                              ))
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                      SizedBox(height: 100)
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
